import base64
import email
import imaplib
import os
import re
from email.header import decode_header

import cv2


def mkdir(path):
    folder = os.path.exists(path)
    if not folder:
        os.makedirs(path)


def get_outlook_verify_code():
    code = None
    imap_host = 'outlook.office365.com'
    imap_user = 'jsxlavpgts@outlook.com'
    imap_pass = 'aew362396'

    # 连接到IMAP服务器
    mail = imaplib.IMAP4_SSL(imap_host)
    mail.login(imap_user, imap_pass)

    # 选择邮箱中的收件箱
    mail.select('inbox')

    # 搜索所有邮件
    status, messages = mail.search(None, 'UNSEEN')

    # 获取邮件ID列表
    email_ids = messages[0].split()

    # 获取最新的5封邮件
    latest_email_ids = email_ids[-5:]

    for email_id in latest_email_ids[-1::-1]:
        # 获取邮件数据
        status, msg_data = mail.fetch(email_id, '(RFC822)')

        # 解析邮件
        msg = email.message_from_bytes(msg_data[0][1])

        # 获取邮件的主题
        subject, encoding = decode_header(msg["Subject"])[0]
        if isinstance(subject, bytes):
            subject = subject.decode(encoding if encoding else 'utf-8')

        # 获取邮件的发件人
        from_ = msg.get("From")
        if 'Shopee' in from_ and 'Shopee: Use OTP To Verify Your Identity' in subject:
            body = msg.get_payload(decode=True).decode()
            start = body.find('Your Shopee OTP Code is:')
            end = body.find('Valid for 15 mins.')
            code = body[start+len('Your Shopee OTP Code is:') : end].strip().replace("`",'')
            code = re.search("<b>[\d]{6}</b>", code).group()[3:9]
    # 关闭连接
    mail.logout()
    return code

def get_boind(image, si):
    sw,sh = si.shape[:2]
    # 转换为灰度图像
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 进行边缘检测
    edges = cv2.Canny(gray, 50, 150)

    # 查找轮廓
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for con in contours:
        # 获取轮廓的边界框
        x, y, w, h = cv2.boundingRect(con)
        if abs(sw - w) <5 and abs(sh - h) < 5:
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
    cv2.imshow("1",image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def _tran_canny(image):
    """消除噪声"""
    image = cv2.GaussianBlur(image, (3, 3), 0)
    return cv2.Canny(image, 50, 150)


def detect_displacement(img_slider_path, image_background_path):
    """detect displacement"""
    # # 参数0是灰度模式
    image = cv2.imread(img_slider_path, 0)
    template = cv2.imread(image_background_path, 0)

    # 寻找最佳匹配
    res = cv2.matchTemplate(_tran_canny(image), _tran_canny(template), cv2.TM_CCOEFF_NORMED)
    # 最小值，最大值，并得到最小值, 最大值的索引
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

    top_left = max_loc[0]  # 横坐标
    # 展示圈出来的区域
    x, y = max_loc  # 获取x,y位置坐标

    w, h = image.shape[::-1]  # 宽高
    cv2.rectangle(template, (x, y), (x + w, y + h), (7, 249, 151), 2)
    cv2.imwrite(r'C:\Users\18222\Desktop\target.png', template)
    # cv2.imshow('1', template)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    return top_left

def img2base64(path):
    with open(path, "rb") as image_file:
        image_data = image_file.read()
        # 将图片数据编码为 base64
        base64_encoded_data = base64.b64encode(image_data)
        # 将 base64 字节数据转换为字符串
        base64_string = base64_encoded_data.decode("utf-8")
        return base64_string

def data2base64(data):
    base64_encoded_data = base64.b64encode(data)
    # 将 base64 字节数据转换为字符串
    base64_string = base64_encoded_data.decode("utf-8")
    return base64_string